/*
 * TextListEx.java
 *
 * Created on 17 Июнь 2007 г., 21:36
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package chatty.ui;

import DrawControls.*;
import DrawControls.icons.Icon;
import DrawControls.text.Par;
import DrawControls.text.Parser;
import java.util.*;
import javax.microedition.lcdui.*;
import chatty.*;
import chatty.cl.*;
import chatty.comm.*;
import chatty.search.*;
import chatty.ui.menu.*;
import chatty.ui.base.*;
import chatty.ui.timers.*;
import chatty.util.*;

/**
 *
 * @author vladimir
 */
public class TextListEx extends TextList implements SelectListener {
    private MenuModel menu;

    public TextListEx(String title) {
        super(title);
        setFontSet(GraphicsEx.chatFontSet);
    }    

    
    public void copy(boolean all) {
        String text = all ? getAllText() : getCurrText();
        if (null != text) {
            ChattyUI.setClipBoardText(getCaption(), text);
        }
    }
	public void copy_add() {
        String text = getCurrText();
        if (null != text) {
            ChattyUI.setClipBoardText(getCaption(), ChattyUI.getClipBoardText(false) + "\n" + text);
        }
    }
    protected MenuModel getMenu() {
        return menu;
    }
    public final void setMenu(MenuModel menu, int backCode, int defCode) {
        this.menu = menu;
        setMenuCodes(backCode, defCode);
        updateSoftLabels();
        invalidate();
    }
    private void updateSoftLabels() {
        MenuModel model = getMenu();
        String more = null;
        String ok = null;
        if (null != model) {
            more = "menu";
            ok = model.getItemText(defaultCode);
        }
        setSoftBarLabels(more, "back");
    }
    protected void restoring() {
        updateSoftLabels();
    }

    protected void itemSelected() {
        if (-2 == defaultCode) {
            if (-1 != getCurrTextIndex()) {
                Chatty.openUrl(getCurrText());
            }
        } else {
            super.itemSelected();
        }
    }
    //////////////////////////////////////////////////////////////////////////////
    //                                                                          //
    // About                                                                    //
    //                                                                          //
    //////////////////////////////////////////////////////////////////////////////
    // String for recent version
    private static final int MENU_UPDATE   = 0;
    private static final int MENU_LAST     = 1;
    private static final int MENU_BACK     = 2;
    private static final int MENU_OPENURL  = -2;
    
    public void initAbout() {
        System.gc();
        System.gc();
        long freeMem = Runtime.getRuntime().freeMemory() / 1024;
        
        lock();
        clear();

        setFontSet(GraphicsEx.chatFontSet);
        
        setCaption(ResBundle.getString("about"));
        
        final String commaAndSpace = ", ";
        
        String[] params = Util.explode(ResBundle.getString("about_info"), '\n');
        addPlainText("\n " + params[0] + "\n\n", THEME_TEXT);
        addPlainText("" + params[2] + "\n", THEME_TEXT);
        for (int i = 3; i < params.length; ++i) {
            int end = params[i].indexOf(':');
            if (-1 == end) {
                addPlainText("\n", THEME_TEXT);
            } else {
                String key = params[i].substring(0, end);
                String value = params[i].substring(end + 1).trim();
                if (value.startsWith("http://")) {
                    addUrl(key, value, uiBigTextIndex++);
                } else {
                    addAboutParam(key, value);
                }
            }
        }

        String partner = Chatty.getAppProperty("Chatty-Partner", null);
        if (!StringConvertor.isEmpty(partner)) {
            addUrl("Partner", StringConvertor.cut(partner, 50), uiBigTextIndex++);
        }
        addPlainText("\n", THEME_TEXT);

        String midpInfo = Chatty.microeditionPlatform;
        if (null != Chatty.microeditionProfiles) {
            midpInfo += commaAndSpace + Chatty.microeditionProfiles;
        }
        String locale = System.getProperty("microedition.locale");
        if (null != locale) {
            midpInfo += commaAndSpace + locale;
        }
        addAboutParam("midp_info", midpInfo);
        addAboutParam("free_heap", freeMem + ResBundle.getString("kb"));
        addAboutParam("total_mem", (Runtime.getRuntime().totalMemory() / 1024)
                + ResBundle.getString("kb"));
        
        if (null != Chatty.lastDate) {
            addAboutParam("latest_ver", Chatty.lastDate);
        }
        
        MenuModel menu = new MenuModel(MenuModel.MENU_LEFT);
        menu.addItem("get_last_version", Chatty.icons.iconAt(Chatty.ICON_GOTO_URL),  MENU_LAST);
        // #sijapp cond.if target is "MIDP2" | target is "MOTOROLA"#
        menu.addItem("update",           Chatty.optionsIcons.iconAt(Chatty.ICON_NETWORK), 	MENU_UPDATE);
        // #sijapp cond.end#
        menu.addItem("back", 			 Chatty.icons.iconAt(Chatty.ICON_BACK), 		MENU_BACK);
        menu.setActionListener(this);
        setMenu(menu, MENU_BACK, -2);
        unlock();
    }

    private void addAboutParam(String langStr, String str) {
        addPlainText(ResBundle.getString(langStr) + ": ", THEME_TEXT);
        addPlainText(str, THEME_PARAM_VALUE);
        addPlainText("\n", THEME_TEXT);
    }

    private void addUrl(String langStr, String url, int id) {
        addPlainText(ResBundle.getString(langStr) + ":\n", THEME_TEXT);
        defaultParser = null;
        Parser line = createParser(id);
        line.addText(url, THEME_PARAM_VALUE, FONT_STYLE_PLAIN);
        addPar(line);
    }

    private final void addPlainText(String text, byte colorType) {
        getDefaultParser().addText(text, colorType, FONT_STYLE_PLAIN);
        getDefaultParser().commit();
	}

    ///////////////////////////////////////////////////////////////////////////
    private Parser defaultParser;
    public final Parser getDefaultParser() {
        if ((0 < getSize()) && (null != defaultParser)) {
            Par last = getPar(getSize() - 1);
            if (-1 == last.index) {
                return defaultParser;
            }
        }
        defaultParser = createParser(-1);
        addPar(defaultParser);
        return defaultParser;
	}
    ///////////////////////////////////////////////////////////////////////////
    private static final int URL_MENU_GOTO = 10;
    private static final int URL_MENU_ADD = 11;
    private static final int URL_MENU_COPY = 12;
    // #sijapp cond.if target is "MOTOROLA" | target is "MIDP2"#
    public TextListEx gotoURL(String text) {
        Vector urls = Util.parseMessageForURL(text);
        if (null == urls) return null;

        setCaption(ResBundle.getString("goto_url"));
        MenuModel menu = new MenuModel(MenuModel.MENU_LEFT);
        menu.addItem("select",	 Chatty.chatIcons.iconAt(Chatty.ICON_GOTO_URL),	URL_MENU_GOTO);
        menu.addItem("copy_text",Chatty.chatIcons.iconAt(Chatty.ICON_COPY), 	URL_MENU_COPY);
        menu.addItem("back",   	 Chatty.icons.iconAt(Chatty.ICON_BACK), 	MENU_BACK);
        menu.setActionListener(this);
        setMenu(menu, MENU_BACK, URL_MENU_GOTO);
        clear();
        for (int i = 0 ; i < urls.size(); ++i) {
            Parser url = createParser(i);
            url.addText((String)urls.elementAt(i), THEME_TEXT, FONT_STYLE_PLAIN);
            addPar(url);
        }
        return this;
    }
    // #sijapp cond.end#
    
    ///////////////////////////////////////////////////////////////////////////
    private String header = null;
    protected int uiBigTextIndex = 0;
    
    public void setHeader(String header) {
        this.header = header;
    }

    private void addHeader() {
        if (null != header) {
            Parser line = createParser(-1);
            line.addText(ResBundle.getString(header),
                    THEME_TEXT, FONT_STYLE_BOLD);
            addPar(line);
            header = null;
        }
    }

    public void addParam(String langStr, String str) {
        if (!StringConvertor.isEmpty(str)) {
            addHeader();
            int id = uiBigTextIndex++;
            Parser line = createParser(id);
            line.addText(ResBundle.getString(langStr) + ": ",
                    THEME_TEXT, FONT_STYLE_PLAIN);
            line.addText(str, THEME_PARAM_VALUE, FONT_STYLE_PLAIN);
            addPar(line);
        }
    }
    
    public void addParamImage(String langStr, Icon img) {
        if (null != img) {
            addHeader();
            int id = uiBigTextIndex++;
            Parser line = createParser(id);
            if (!StringConvertor.isEmpty(langStr)) {
                line.addText(ResBundle.getString(langStr) + ": ",
                        THEME_TEXT, FONT_STYLE_PLAIN);
            }
            line.addImage(img);
            addPar(line);
        }
    }
    
    ///////////////////////////////////////////////////////////////////////////
    public void addItem(String str, int code, boolean active) {
        byte type = active ? FONT_STYLE_BOLD : FONT_STYLE_PLAIN;
        Parser item = createParser(code);
        item.useMinHeight();
        item.addText(str, THEME_TEXT, type);
        addPar(item);
    }

    ///////////////////////////////////////////////////////////////////////////
	public void clear() {
        uiBigTextIndex = 0;
        setHeader(null);
        super.clear();
    }
    
    ///////////////////////////////////////////////////////////////////////////
    public void select(Select select, MenuModel model, int cmd) {
        switch (cmd) {
            // #sijapp cond.if target is "MIDP2" | target is "MOTOROLA"#
            case MENU_UPDATE:
                GetVersion.updateProgram();
                break;
            // #sijapp cond.end#

            case MENU_LAST:
                new GetVersion(GetVersion.TYPE_DATE).get();
                restore();
                break;

            case MENU_BACK:
                back();
                clear();
                break;

            // #sijapp cond.if target is "MIDP2" | target is "MOTOROLA"#
            case URL_MENU_GOTO:
                back();
                Chatty.openUrl(getCurrText());
                break;
            // #sijapp cond.end#

            case URL_MENU_COPY:
                copy(false);
                restore();
                break;

            case URL_MENU_ADD:
                Chatty.openUrl("xmpp:" + Util.getUrlWithoutProtocol(getCurrText()));
                break;
        }
    }
}